
package com.hlkj.pay.app.merchant.ext.impl.easypay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessAuthQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.easypay.dto.EasyPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.EasyPaySignUtil;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.HttpUtils;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigAppIdDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigListDto;
import com.hlkj.pay.dto.pay.PayCommonAppDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.StringPool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HlpayTeam
 * @date 2024/10/16 9:10
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class EasyPayMerchantAccessConfigHandler extends EasyPayMerchantCommonParamsHandle {

    @Value("${hlkj.domain}")
    private String domainHost;

    /**
     * 微信/支付宝 子商户查询
     * 
     * @param channelMerchantBusinessContext
     */
    public void processSubMerInfoQuery(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();
        // 1. 数据初始化
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            CommonResult<Map<String, String>> paramsCommonResult = EasyPayMerchantParamsHandle.queryMerchant(merchantAccessInfo.getApplyNo(), easyPayConfig);
            Map<String, String> params = paramsCommonResult.getData();
            params.put("MAC", EasyPaySignUtil.md5Sign(params, easyPayConfig.getMd5Key()));
            String url = domain(channelMerchantBusinessContext.isTest());
            log.info("易生商户报备信息查询请求参数:{}", JsonUtils.toJsonString(params));
            String response = HttpUtils.requestPost(url, params);
            log.info("易生商户报备信息查询返回参数:{}", response);
            JSONObject respObj = JsonUtils.parseObj(response);
            if (!"0000".equals(respObj.getStr("retCode"))) {
                channelMerchantBusinessContext.setRemark(respObj.getStr("retMsg"));
                log.error("易生商户报备信息查询异常 message: {}", respObj.getStr("retMsg"));
                return;
            }
            JSONArray funcInfoArr = respObj.getJSONArray("funcInfo");
            List<MerchantAccessAuthDO> merchantAccessAuthList = new ArrayList<>();
            for (int i = 0; i < funcInfoArr.size(); i++) {
                JSONObject funcInfo = funcInfoArr.getJSONObject(i);
                MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                merchantAccessAuthDO.setAuthUrl("");
                merchantAccessAuthDO.setAuthCode("");
                switch (funcInfo.getStr("funcId")) {
                    case "2":
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
                        merchantAccessAuthDO.setSubMchId(funcInfo.getStr("alipayId"));
                        if (!StringUtils.hasText(funcInfo.getStr("alipayCertUrl"))) {
                            merchantAccessAuthDO.setAuthUrl(easyPayConfig.getAli_qrcode());
                        } else
                            merchantAccessAuthDO.setAuthUrl(funcInfo.getStr("alipayCertUrl"));
                        break;
                    case "3":
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
                        merchantAccessAuthDO.setSubMchId(funcInfo.getStr("wechatId"));
                        if (StringUtils.hasText(funcInfo.getStr("wechatCertUrl")))
                            merchantAccessAuthDO.setAuthUrl(funcInfo.getStr("wechatCertUrl"));
                        else
                            merchantAccessAuthDO.setAuthUrl(easyPayConfig.getWx_qrcode());
                        break;
                    case "12":
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.UNION_APY.getCode());
                        break;
                    default:
                        continue;
                }

                switch (funcInfo.getStr("state")) {
                    case "0":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY.getCode());
                        break;
                    case "1":
                        if (StringUtils.hasText(merchantAccessAuthDO.getSubMchId()))
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                        else
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                    case "3":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                        break;
                    case "9":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                        break;
                    case "X":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                }
                merchantAccessAuthDO.setRejectReason(funcInfo.getStr("retMsg"));
                merchantAccessAuthList.add(merchantAccessAuthDO);
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_CONFIG);
            channelMerchantBusinessContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生商户报备信息查询请求失败,失败信息 message: {}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("易生商户报备信息查询请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
        }
    }

    public void wechatConfigInit(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();

            List<PayCommonAppDto> payCommonAppList = channelMerchantBusinessContext.getPayCommonAppList();
            List<PayCommonAppDto> wechatCommonApp = null;
            if (!CollectionUtils.isEmpty(payCommonAppList)) {
                wechatCommonApp = payCommonAppList.stream().filter(payCommonAppDto -> PayEnums.PAY_TYPE.WECHAT.getCode().equals(payCommonAppDto.getPayWayDO().getType()))
                        .collect(Collectors.toList());
            }
            // 没有微信执行 配置完成
            if (CollectionUtils.isEmpty(wechatCommonApp)) {
                return;
            }
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessAuthList().stream()
                    .filter(merchantAccessAuthDO -> PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())).collect(Collectors.toList());

            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);

            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthList) {
                if (!StringUtils.hasText(merchantAccessAuthDO.getSubMchId())) {
                    continue;
                }
                for (PayCommonAppDto payCommonAppDto : wechatCommonApp) {
                    CommonResult<Map<String, String>> authCommonResult = EasyPayMerchantParamsHandle.wxConfigInit(easyPayConfig, merchantAccessAuthDO, payCommonAppDto.getAppId(), "");
                    Map<String, String> authParams = authCommonResult.getData();
                    authParams.put("MAC", EasyPaySignUtil.md5Sign(authParams, easyPayConfig.getMd5Key()));
                    String authUrl = domain(channelMerchantBusinessContext.isTest());
                    log.info("易生初始化微信参数配置APPID请求参数:{}", JsonUtils.toJsonString(authParams));
                    String authResponse = HttpUtils.requestPost(authUrl, authParams);
                    log.info("易生初始化微信参数配置APPID返回参数:{}", authResponse);
//                    JSONObject authResp = JsonUtils.parseObj(authResponse);
//                    if (!"0000".equals(authResp.getStr("retCode"))) {
//                        channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
//                        channelMerchantBusinessContext.setRemark(authResp.getStr("retMsg"));
//                        log.error("易生初始化微信参数配置异常 message: {}", authResp.getStr("retMsg"));
//                        return;
//                    }

                    String authPath = domainHost + StringPool.SLASH;;
                    authCommonResult = EasyPayMerchantParamsHandle.wxConfigInit(easyPayConfig, merchantAccessAuthDO, "", authPath);
                    authParams = authCommonResult.getData();
                    authParams.put("MAC", EasyPaySignUtil.md5Sign(authParams, easyPayConfig.getMd5Key()));
                    authUrl = domain(channelMerchantBusinessContext.isTest());
                    log.info("易生初始化微信参数配置授权目录请求参数:{}", JsonUtils.toJsonString(authParams));
                    authResponse = HttpUtils.requestPost(authUrl, authParams);
                    log.info("易生初始化微信参数配置授权目录返回参数:{}", authResponse);

                }
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_AUTH);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生初始化微信参数配置请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("易生初始化微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantBusinessContext
     */
    public void processWxAuth(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();
            MerchantAccessAuthDO merchantAccessAuth = channelMerchantBusinessContext.getMerchantAccessAuth();
            CommonResult<Map<String, String>> authCommonResult = EasyPayMerchantParamsHandle.wxConfig(channelMerchantBusinessContext, easyPayConfig, merchantAccessAuth);
            Map<String, String> authParams = authCommonResult.getData();
            authParams.put("MAC", EasyPaySignUtil.md5Sign(authParams, easyPayConfig.getMd5Key()));
            String authUrl = domain(channelMerchantBusinessContext.isTest());
            log.info("易生微信参数配置请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.requestPost(authUrl, authParams);
            log.info("易生微信参数配置返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"0000".equals(authResp.getStr("retCode"))) {
                channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantBusinessContext.setRemark(authResp.getStr("retMsg"));
                log.error("易生微信参数配置异常 message: {}", authResp.getStr("retMsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生微信参数配置请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("易生微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    public void channelSplit(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantBusinessContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();
            CommonResult<Map<String, String>> paramsCommonResult  = EasyPayMerchantParamsHandle.easySplit(channelMerchantBusinessContext, easyPayConfig);
            Map<String, String> params = paramsCommonResult.getData();
            params.put("MAC", EasyPaySignUtil.md5SignSplit(params, easyPayConfig.getMd5Key()));

            String url = domain(channelMerchantBusinessContext.isTest());
            log.info("易生微信/支付宝拆分请求参数:{}", JsonUtils.toJsonString(params));
            String response = HttpUtils.requestPost(url, params);
            log.info("易生微信/支付宝拆分返回参数:{}", response);
            JSONObject respObj = JsonUtils.parseObj(response);
            if (!"0000".equals(respObj.getStr("retCode"))) {
                channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantBusinessContext.setRemark("易生微信/支付宝拆分失败：" + respObj.getStr("retMsg"));
                log.error("易生微信/支付宝拆分失败 message: {}", respObj.getStr("retMsg"));
//                MerchantAccessAuthDO merchantAccessAuthDO = channelMerchantBusinessContext.getMerchantAccessAuthDO();
//                MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
//                merchantAccessAuthDO.setAccessId(merchantAccessInfo.getId());
//                merchantAccessAuthDO.setSn(merchantAccessInfo.getSn());
//                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_FAIL.getCode());
//                merchantAccessAuthDO.setRejectReason(channelMerchantBusinessContext.getRemark());
                return;
            }
            channelMerchantBusinessContext.setMerchantAccessAuthDO(null);
            channelMerchantBusinessContext.setProcessStatus(Boolean.TRUE);
            channelMerchantBusinessContext.setRemark("拆分成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生微信/支付宝拆分请求异常,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("易生微信/支付宝拆分请求异常,异常信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信参数配置查询
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxConfigQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthList();
            // 没有微信报备 执行支付宝认证
            if (CollectionUtils.isEmpty(merchantAccessAuthList)) {
                channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
                return;
            }
            String url = domain(channelMerchantAccessAuthQueryContext.isTest());
            MerchantWechatConfigListDto merchantWechatConfigListDto = new MerchantWechatConfigListDto();
            List<MerchantWechatConfigAppIdDto> appIdList = new ArrayList<>();
            List<String> jsApiPath = new ArrayList<>();
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthList) {
                if (!PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())) {
                    log.info("易生微信配置查询 非报备非微信类型直接返回 type:{},subMchId:{}", merchantAccessAuthDO.getType(), merchantAccessAuthDO.getSubMchId());
                    continue;
                }
                if (StringUtils.hasText(merchantAccessAuthDO.getMchId())) {
                    log.info("易生微信配置查询 微信子商户号不存在 accessId:{},subMchId:{}", merchantAccessAuthDO.getAccessId(), merchantAccessAuthDO.getSubMchId());
                    continue;
                }
                CommonResult<Map<String, String>> paramsCommonResult = EasyPayMerchantParamsHandle.wxConfigQuery(easyPayConfig, merchantAccessAuthDO);
                Map<String, String> params = paramsCommonResult.getData();
                params.put("MAC", EasyPaySignUtil.md5Sign(params, easyPayConfig.getMd5Key()));

                log.info("易生微信配置查询请求参数:{}", JsonUtils.toJsonString(params));
                String response = HttpUtils.requestPost(url, params);
                log.info("易生微信配置查询返回参数:{}", response);
                JSONObject respObj = JsonUtils.parseObj(response);
                if (!"0000".equals(respObj.getStr("retCode"))) {
                    channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                    channelMerchantAccessAuthQueryContext.setRemark(respObj.getStr("retMsg"));
                    log.error("易生微信配置查询异常 message: {}", respObj.getStr("retMsg"));
                }
                try {
                    if (!CollectionUtils.isEmpty(respObj.getJSONObject("configInfo"))) {
                        JSONObject configObj = respObj.getJSONObject("configInfo");
                        if (configObj.containsKey("appid_config_list")) {
                            configObj.getJSONArray("appid_config_list").stream().forEach(resp -> {
                                JSONObject config = (JSONObject)resp;
                                MerchantWechatConfigAppIdDto merchantWechatConfigAppIdDto = new MerchantWechatConfigAppIdDto();
                                merchantWechatConfigAppIdDto.setSubAppid(config.getStr("sub_appid"));
                                merchantWechatConfigAppIdDto.setSubscribeAppid(config.getStr("subscribe_appid"));
                                appIdList.add(merchantWechatConfigAppIdDto);
                            });
                        }
                        if (configObj.containsKey("jsapi_path_list")) {
                            JSONArray arr =  configObj.getJSONArray("jsapi_path_list");
                            for (int i = 0; i < arr.size(); i++) {
                                jsApiPath.add(arr.get(i).toString());
                            }
//                            configObj.getJSONArray("jsapi_path_list").stream().forEach(resp -> {
//                                jsApiPath.add(resp.toString());
//                            });
                        }
                    }
//                    if (!CollectionUtils.isEmpty(respData.getJsapiPathList())) {
//                        jsApiPath.addAll(respData.getJsapiPathList());
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    channelMerchantAccessAuthQueryContext.setProcessStatus(false);
                    channelMerchantAccessAuthQueryContext.setRemark(e.getMessage());
                }
            }
            merchantWechatConfigListDto.setAppIdList(appIdList);
            merchantWechatConfigListDto.setJsApiPath(jsApiPath);
            channelMerchantAccessAuthQueryContext.setMerchantWechatConfigListDto(merchantWechatConfigListDto);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生微信配置查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantAccessAuthQueryContext.setRemark("易生微信配置查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessAuthQueryContext.getMerchantAccessInfo();

            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthDbList();
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);

            CommonResult<Map<String, String>> authCommonResult = EasyPayMerchantParamsHandle.queryMerchant(merchantAccessInfo.getApplyNo(), easyPayConfig);
            Map<String, String> authParams = authCommonResult.getData();
            authParams.put("MAC", EasyPaySignUtil.md5Sign(authParams, easyPayConfig.getMd5Key()));
            String authUrl = domain(channelMerchantAccessAuthQueryContext.isTest());
            log.info("易生微信认证查询请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.requestPost(authUrl, authParams);
            log.info("易生微信认证查询返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"0000".equals(authResp.getStr("retCode"))) {
                channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessAuthQueryContext.setRemark(authResp.getStr("retMsg"));
                log.error("易生微信认证查询异常 message: {}", authResp.getStr("retMsg"));
                return;
            }

            JSONArray funcInfoArr = authResp.getJSONArray("funcInfo");

            for (int i = 0; i < funcInfoArr.size(); i++) {
                JSONObject funcInfo = funcInfoArr.getJSONObject(i);
                if (!"3".equals(funcInfo.getStr("funcId"))) {
                    continue;
                }
                if (!StringUtils.hasText(funcInfo.getStr("wechatId"))) {
                    continue;
                }
                MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.stream().filter(item -> funcInfo.getStr("wechatId").equals(item.getSubMchId())).findFirst().orElse(null);
                if (merchantAccessAuthDO == null) {
                    merchantAccessAuthDO = new MerchantAccessAuthDO();
                    merchantAccessAuthList.add(merchantAccessAuthDO);
                }

                merchantAccessAuthDO.setSubMchId(funcInfo.getStr("wechatId"));

                if (StringUtils.hasText(funcInfo.getStr("wechatCertUrl")))
                    merchantAccessAuthDO.setAuthUrl(funcInfo.getStr("wechatCertUrl"));
                else
                    merchantAccessAuthDO.setAuthUrl(easyPayConfig.getWx_qrcode());
                switch (funcInfo.getStr("state")) {
                    case "0":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY.getCode());
                        break;
                    case "1":
                        if (StringUtils.hasText(merchantAccessAuthDO.getSubMchId()))
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                        else
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                    case "3":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                        break;
                    case "9":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                        break;
                    case "X":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                }
                if (MerchantEnum.MERCHANT_AUTH_STATUS.from(merchantAccessAuthDO.getStatus()) == MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE) {
                    CommonResult<Map<String, String>> reqCommonResult = EasyPayMerchantParamsHandle.wxAuthQuery(easyPayConfig, merchantAccessAuthDO);
                    Map<String, String> reqParams = reqCommonResult.getData();
                    reqParams.put("MAC", EasyPaySignUtil.md5Sign(reqParams, easyPayConfig.getMd5Key()));
                    log.info("易生微信授权查询请求参数:{}", JsonUtils.toJsonString(reqParams));
                    String authQueryResponse = HttpUtils.requestPost(authUrl, reqParams);
                    log.info("易生微信授权查询返回参数:{}", authQueryResponse);
                    JSONObject authQueryResp = JsonUtils.parseObj(authQueryResponse);
                    if (!"0000".equals(authQueryResp.getStr("retCode"))) {
                        channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                        channelMerchantAccessAuthQueryContext.setRemark(authQueryResp.getStr("retMsg"));
                        log.error("易生微信授权查询异常 message: {}", authQueryResp.getStr("retMsg"));
                        return;
                    }
                    switch (authQueryResp.getStr("authorizeState")) {
                        case "AUTHORIZE_STATE_AUTHORIZED":
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
                    }
                }
                merchantAccessAuthDO.setRejectReason(funcInfo.getStr("retMsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生微信认证查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantAccessAuthQueryContext.setRemark("易生微信认证查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信 appid配置，
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processAliAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<EasyPayConfig> easyPayConfigCommonResult = channelConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig());
        // 配置转换
        if (!easyPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(easyPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }

        try {
            EasyPayConfig easyPayConfig = easyPayConfigCommonResult.getData();
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessAuthQueryContext.getMerchantAccessInfo();

            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantAccessAuthQueryContext.getMerchantAccessAuthDbList();
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.FINISH);

            CommonResult<Map<String, String>> authCommonResult = EasyPayMerchantParamsHandle.queryMerchant(merchantAccessInfo.getApplyNo(), easyPayConfig);
            Map<String, String> authParams = authCommonResult.getData();
            authParams.put("MAC", EasyPaySignUtil.md5Sign(authParams, easyPayConfig.getMd5Key()));
            String authUrl = domain(channelMerchantAccessAuthQueryContext.isTest());
            log.info("易生支付宝认证查询请求参数:{}", JsonUtils.toJsonString(authParams));
            String authResponse = HttpUtils.requestPost(authUrl, authParams);
            log.info("易生支付宝认证查询返回参数:{}", authResponse);
            JSONObject authResp = JsonUtils.parseObj(authResponse);
            if (!"0000".equals(authResp.getStr("retCode"))) {
                channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessAuthQueryContext.setRemark(authResp.getStr("retMsg"));
                log.error("易生支付宝认证查询异常 message: {}", authResp.getStr("retMsg"));
            }

            JSONArray funcInfoArr = authResp.getJSONArray("funcInfo");
            for (int i = 0; i < funcInfoArr.size(); i++) {
                JSONObject funcInfo = funcInfoArr.getJSONObject(i);
                if (!"2".equals(funcInfo.getStr("funcId"))) {
                    continue;
                }
                if (!StringUtils.hasText(funcInfo.getStr("alipayId"))) {
                    continue;
                }
                MerchantAccessAuthDO merchantAccessAuthDO = merchantAccessAuthList.stream().filter(item -> funcInfo.getStr("alipayId").equals(item.getSubMchId())).findFirst().orElse(null);
                if (merchantAccessAuthDO == null) {
                    merchantAccessAuthDO = new MerchantAccessAuthDO();
                    merchantAccessAuthList.add(merchantAccessAuthDO);
                }

                merchantAccessAuthDO.setSubMchId(funcInfo.getStr("alipayId"));
                if (StringUtils.hasText(funcInfo.getStr("alipayCertUrl")))
                    merchantAccessAuthDO.setAuthUrl(funcInfo.getStr("alipayCertUrl"));
                else
                    merchantAccessAuthDO.setAuthUrl(easyPayConfig.getAli_qrcode());

                switch (funcInfo.getStr("state")) {
                    case "0":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY.getCode());
                        break;
                    case "1":
                        if (StringUtils.hasText(merchantAccessAuthDO.getSubMchId()))
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                        else
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                    case "3":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                        break;
                    case "9":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                        break;
                    case "X":
                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                        break;
                }
                merchantAccessAuthDO.setRejectReason(funcInfo.getStr("retMsg"));
                if (MerchantEnum.MERCHANT_AUTH_STATUS.from(merchantAccessAuthDO.getStatus()) == MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE) {
                    CommonResult<Map<String, String>> reqCommonResult = EasyPayMerchantParamsHandle.aliAuthQuery(easyPayConfig, merchantAccessAuthDO);
                    Map<String, String> reqParams = reqCommonResult.getData();
                    reqParams.put("MAC", EasyPaySignUtil.md5Sign(reqParams, easyPayConfig.getMd5Key()));
                    log.info("易生支付宝授权查询请求参数:{}", JsonUtils.toJsonString(reqParams));
                    String authQueryResponse = HttpUtils.requestPost(authUrl, reqParams);
                    log.info("易生支付宝授权查询返回参数:{}", authQueryResponse);
                    JSONObject authQueryResp = JsonUtils.parseObj(authQueryResponse);
                    if (!"0000".equals(authQueryResp.getStr("retCode"))) {
                        channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
                        channelMerchantAccessAuthQueryContext.setRemark(authQueryResp.getStr("retMsg"));
                        log.error("易生支付宝授权查询异常 message: {}", authQueryResp.getStr("retMsg"));
                        return;
                    }
                    JSONObject authObj = authQueryResp.getJSONObject("data");
                    switch (authObj.getStr("check_result")) {
                        case "AUTHORIZED":
                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("易生支付宝认证查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantAccessAuthQueryContext.setRemark("易生支付宝认证查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }
}

